<template>
  <div>
    <div class="search_container">
      <el-row :gutter="6" style="margin-bottom: 10px;">
        <el-col :span="8">
          <span>代发单号</span>
          <el-input v-model="kkId" placeholder="快递单号" label="代发单号" class="input"></el-input>
        </el-col>
        <el-col :span="8">
          <span>代发快递</span>
          <el-select v-model="kkType" placeholder="请选择快递" clearable>
            <el-option
              v-for="item in expressOptions"
              :key="item.id"
              :label="item.kkDesc"
              :value="item.kkType"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="8">
          <span>代发礼品</span>
          <el-select v-model="gift" placeholder="请选择商品">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.resourceDesc"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row :gutter="6" style="margin-bottom: 10px;">
        <el-col :span="8">
          <span>订单编号</span>
          <el-input v-model="outOrderId" placeholder="订单编号" label="订单编号" class="input"></el-input>
        </el-col>
        <el-col :span="8">
          <span>订单状态</span>
          <el-select v-model="status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row :gutter="6" style="margin-bottom: 10px;">
        <el-col :span="8">
          <span>开始日期</span>
          <el-date-picker
            v-model="start"
            type="date"
            placeholder="选择日期"
            format="yyyyMMdd"
            value-format="yyyyMMdd"
          ></el-date-picker>
        </el-col>
        <el-col :span="8">
          <span>结束日期</span>
          <el-date-picker v-model="end" type="date" placeholder="选择日期" format="yyyyMMdd"></el-date-picker>
        </el-col>
      </el-row>
      <el-row :gutter="6" style="margin-bottom: 10px;">
        <el-col :span="8">
          <el-button type="primary" @click="search()">搜索</el-button>
          <el-button type="primary" @click="exportVisible = true">导出订单</el-button>
        </el-col>
      </el-row>
    </div>
    <el-dialog title="请选择导出格式" :visible.sync="exportVisible">
      <el-radio v-model="exportType" label="csv">.csv格式【适合wps打开】</el-radio>
      <el-radio v-model="exportType" label="excel">.xls格式【适合excel打开】</el-radio>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmExportType">确 定</el-button>
      </div>
    </el-dialog>

    <div class="table_container">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column property="kkDesc" label="快递类型" width="150"></el-table-column>
        <el-table-column property="kkId" label="快递单号" width="180"></el-table-column>
        <el-table-column property="giftResourceDesc" label="礼品" width="180"></el-table-column>
        <el-table-column label="收货地址" width="300">
          <template
            slot-scope="scope"
          >{{ `${scope.row.receiverName}, ${scope.row.receiverTel}, ${scope.row.receiverAddress}`}}</template>
        </el-table-column>
        <el-table-column property="gmtCreate" label="下单时间" width="180"></el-table-column>
        <el-table-column label="发货地址" width="300">
          <template
            slot-scope="scope"
          >{{`${scope.row.name}; ${scope.row.tel}; ${scope.row.province} ${scope.row.city} ${scope.row.region} ${scope.row.detail}`}}</template>
        </el-table-column>
        <el-table-column label="订单金额" width="130">
          <template slot-scope="scope">{{ "¥" + `${scope.row.amount/100}` + "金币" }}</template>
        </el-table-column>
        <el-table-column label="备注信息" width="80">
          <template slot-scope="scope">{{ scope.row.memo === '' ? '空' : scope.row.memo }}</template>
        </el-table-column>
        <el-table-column label="订单状态">
          <template slot-scope="scope">{{ statusString(scope.row.status) }}</template>
        </el-table-column>
      </el-table>
      <div class="Pagination" style="text-align: left;margin-top: 10px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 50, 80, 100]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import headTop from "@/components/headTop";
import { getGiftList } from "@/api/gift";
import { getExpressList } from "@/api/info";
import { getAllOrderDetail, exportAllOrderDetail } from "@/api/order";
import moment from "moment";
import csv from "csvtojson";
// import XLSX from "xlsx";

export default {
  data() {
    return {
      tableData: [],
      currentRow: null,
      offset: 0,
      limit: 20,
      count: 0,
      currentPage: 1,
      options: [],
      expressOptions: [],
      statusOptions: [
        {
          value: "",
          label: "全部"
        },
        {
          value: "CREATE",
          label: "未支付"
        },
        {
          value: "ENABLE",
          label: "已支付"
        },
        {
          value: "TO_PRINT",
          label: "待打印"
        },
        {
          value: "FINISHED",
          label: "已打印"
        }
      ],
      gift: -1,
      kkType: "",
      status: "",
      start: "",
      end: undefined,
      kkId: "",
      outOrderId: "",
      price: {
        shengtong_quanzhou0: 3,
        shengtong_changzhou0: 3,
        shengtong_quanzhou1: 3,
        shengtong_changzhou1: 3,
        shengtong_quanzhou2: 2,
        shengtong_changzhou2: 2,
        TT1: 3,
        TT2: 3,
        TT0: 3
      },
      tableLoading: false,
      fullscreenLoading: false,
      exportType: "csv",
      exportVisible: false
    };
  },
  components: {
    headTop
  },
  created() {
    // this.initData();
    this.getGiftList();
    this.getExpressList();
    this.getAllOrderDetail();
  },
  methods: {
    async getExpressList() {
      try {
        const result = await getExpressList();
        if (result.status === 200) {
          this.expressOptions = result.data.data.filter(e => {
            return e.status === "ENABLE" && e.kkType.search(/^API_/) === -1;
          });
        } else {
          throw new Error("快递列表获取失败");
        }
      } catch (err) {
        console.log(err);
      }
    },
    async getGiftList() {
      try {
        let result = await getGiftList(false);
        if (result.status === 200 && result.data.code === 200) {
          let ops = [{ id: -1, resourceDesc: "全部" }];
          let gifts = result.data.data.filter((e, i, a) => {
            return (
              e.status === "ENABLE" && e.resourceDesc.search(/^API_/) === -1
            );
          });
          ops.push(...gifts);
          this.options = ops;
        } else {
          throw new Error("获取数据失败");
        }
      } catch (err) {
        // this.$message.error('获取数据失败')
        console.log("获取数据失败", err);
      }
    },
    checkParam() {
      let params = {
        pageIndex: this.currentPage,
        pageSize: this.limit
      };
      if (this.gift !== -1) {
        params["giftId"] = this.gift;
      }

      if (this.start != null && this.start.length !== 0) {
        params["start"] = this.start;
      }

      if (this.status !== "") {
        params["status"] = this.status;
      }

      if (this.end !== undefined) {
        let endtime = moment(this.end);
        endtime.add(1, "d");
        params["end"] = endtime.format("YYYYMMDD");
      }

      if (this.kkId.length !== 0) {
        params["kkId"] = this.kkId;
      }

      if (this.kkType.length !== 0) {
        params["kkType"] = this.kkType;
      }
      if (this.outOrderId.length !== 0) {
        params["outOrderId"] = this.outOrderId;
      }

      return params;
    },

    confirmExportType() {
      this.exportVisible = false;
      if (this.exportType === "excel") {
        this.exportAllOrderDetailToExcel();
      } else {
        this.exportAllOrderDetailToCSV();
      }
    },
    async exportAllOrderDetailToExcel() {
      const loading = this.$loading({
        lock: true,
        text: "正在加载",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      try {
        const params = this.checkParam();
        let queryString = Object.keys(params)
          .map(key => {
            return (
              encodeURIComponent(key) + "=" + encodeURIComponent(params[key])
            );
          })
          .join("&");
        const result = await exportAllOrderDetail(params);
        if (result.status === 200) {
          csv({})
            .fromString(result.data)
            .then(csvRow => {
              // let filterRows = []

              let filterRows = Object.assign(
                [],
                ...Object.keys(csvRow).map(k => {
                  let row = csvRow[k];
                  return {
                    [k]: Object.assign(
                      {},
                      ...Object.keys(row).map(e => {
                        let v = row[e];
                        return { [e]: v.substring(2, v.length - 1) };
                      })
                    )
                  };
                })
              );
              let wb = XLSX.utils.book_new();
              let ws = XLSX.utils.json_to_sheet(filterRows);
              // let timestamp=new Date().getTime()
              // let myDate = new Date();
              // myDate.getFullYear();    //获取完整的年份(4位,1970-????)
              // myDate.getMonth();       //获取当前月份(0-11,0代表1月)
              // myDate.getDate();        //获取当前日(1-31)
              // myDate.getDay();         //获取当前星期X(0-6,0代表星期天)

              let time2 = moment().format("YYYY-MM-DD");
              XLSX.utils.book_append_sheet(wb, ws, "all");
              XLSX.writeFile(wb, `Export-${time2}.xls`);
            });
        } else {
          throw new Error("获取数据失败");
        }
      } catch (err) {
        // this.$message.error('获取数据失败')
        console.log("获取数据失败", err);
      }
      loading.close();
    },
    async exportAllOrderDetailToCSV() {
      const loading = this.$loading({
        lock: true,
        text: "正在加载",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      // try {
      const params = this.checkParam();
      let queryString = Object.keys(params)
        .map(key => {
          return (
            encodeURIComponent(key) + "=" + encodeURIComponent(params[key])
          );
        })
        .join("&");
      window.open("/v01/user/order_detail/download/list" + "?" + queryString);
      loading.close();
    },

    async getAllOrderDetail() {
      this.tableLoading = true;
      try {
        const params = this.checkParam();
        const result = await getAllOrderDetail(params);
        if (result.status === 200 && result.data.code === 200) {
          this.tableData = result.data.data;
          this.count = result.data.page.total;
        } else {
          throw new Error("获取数据失败");
        }
      } catch (err) {
        // this.$message.error('获取数据失败')
        console.log("获取数据失败", err);
      }
      this.tableLoading = false;
    },

    async search() {
      this.currentPage = 1;
      this.getAllOrderDetail();
    },
    async initData() {},
    handleSizeChange(size) {
      this.limit = size;
      this.getAllOrderDetail();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getAllOrderDetail();
    },
    statusString(status) {
      switch (status) {
        case "CREATE":
          return "未支付";
        case "ENABLE":
          return "已支付";
        case "TO_PRINT":
          return "待打印";
        case "FINISHED":
          return "已打印";
        default:
          return "已取消";
      }
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../style/mixin";
// .fix-width-frame {
//   margin: 0 auto;
//   width: 1000px;
// }

.table_container {
  padding: 20px;
}
.search_container {
  margin: 20px;
  padding: 10px 20px;
  border: 1px solid @bc;
}
.input {
  width: 220px;
}

.el-row {
  font-size: 12px;
  color: #222;
  .el-col {
    span {
      margin-right: 10px;
    }
  }
}
</style>
